package com.yeqing.crazymakercircle.bufferDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileNIOCopyDemo {

    public static void main(String[] args) {
        // 演示复制资源文件
        nioCopyFile("/Users/cyq/Develop/三国/张飞.txt", "/Users/cyq/Develop/三国/张飞111.txt");
    }

    /**
     * nio方式复制文件
     *
     * @param srcPath  源路径
     * @param destPath 目标路径
     */
    public static void nioCopyFile(String srcPath, String destPath) {
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        try {
            //如果目标文件不存在，则新建
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            long startTime = System.currentTimeMillis();

            try (
                    FileInputStream fis = new FileInputStream(srcFile);
                    FileOutputStream fos = new FileOutputStream(destFile);
                    ) {

                FileChannel inChannel = fis.getChannel();
                FileChannel outchannel = fos.getChannel();

                int length = -1;
                // 新建buf，处于写入模式
                ByteBuffer buf = ByteBuffer.allocate(1024);
                // 从输入通道读取到buf
                while ((length = inChannel.read(buf)) != -1) {
                    // buf第一次模式切换：翻转buf，从写入模式变成读取模式
                    buf.flip();
                    int outlength = 0;
                    // 将buf写入到输出的通道
                    while ((outlength = outchannel.write(buf)) != 0) {
                        System.out.println("写入的字节数：" + outlength);
                    }

                    // buf第二次模式切换：清除buf，变成写入模式
                    buf.clear();
                }
                // 强制刷新到磁盘
                outchannel.force(true);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("base复制毫秒数：" + (endTime - startTime));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
